package com.spark.auth.controller;

import com.spark.basecommon.api.R;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.security.oauth2.common.OAuth2AccessToken;
import org.springframework.security.oauth2.provider.endpoint.TokenEndpoint;
import org.springframework.web.HttpRequestMethodNotSupportedException;
import org.springframework.web.bind.annotation.*;
import springfox.documentation.annotations.ApiIgnore;

import java.security.Principal;
import java.util.Map;

/**
 * @author fuqiang
 * @Description 权限控制层
 * @Date 2020/9/29
 */
@RestController
@RequestMapping("/oauth")
@Api(tags = "用户认证中心")
@Slf4j
public class AuthController {
    /**
     * auth2
     */
    @Autowired
    private TokenEndpoint tokenEndpoint;

    @PostMapping("/getToken")
    @ApiOperation(
            value = "认证,获取token"
    )
    @ApiImplicitParams({
            @ApiImplicitParam(name = "grant_type", value = "授权模式", required = true),
            @ApiImplicitParam(name = "client_id", value = "Oauth2客户端ID", required = true),
            @ApiImplicitParam(name = "client_secret", value = "Oauth2客户端秘钥", required = true),
            @ApiImplicitParam(name = "refresh_token", value = "刷新token"),
            @ApiImplicitParam(name = "username", value = "登录用户名"),
            @ApiImplicitParam(name = "password", value = "登录密码")
    })
    public R<OAuth2AccessToken> authorization(@ApiIgnore @RequestBody Principal principal, @ApiIgnore @RequestParam Map<String, String> parameters){
        try {
            OAuth2AccessToken oAuth2AccessToken = tokenEndpoint.postAccessToken(principal,parameters).getBody();
            return R.success(oAuth2AccessToken);
        } catch (HttpRequestMethodNotSupportedException e) {
            log.error(e.getMessage());
        }
        return R.failed("获取token失败");
    }
}
